﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Elysium.Demo;
using Elysium.Demo.Configuracion;
using Elysium.Demo.Ventas;
using Elysium.Demo.Compras;
using Elysium.Demo.CapitalHumano;
using Elysium.Demo.Inventarios;
using Elysium.Demo.Bancos;
using Elysium.Demo.PuntoVenta;
using Elysium.Demo.CRM;
using Elysium.Demo.MiPerfil;
using SIIE_ERP.Codigo;
using System.Data;
using SIIE_ERP.BaseDatos.Configuracion;
using Elysium.Demo.Informes;

namespace Elysium.Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Elysium.Controls.Window
    {
        UsuarioActivo _sesion;
        System.Timers.Timer _t;

        public MainWindow(UsuarioActivo sesion)
        {
            InitializeComponent();
            _sesion = sesion;
            //TIepm
            _t = new System.Timers.Timer();
            _t.AutoReset = false;
            _t.Elapsed += new System.Timers.ElapsedEventHandler(ValidarSesion);
            //_t.Interval = 60000; // Verificar si la sesion esta activa cada minuto
            _t.Interval = 10000; // Verificar si la sesion esta activa cada Segundo
            _t.Start();


            //VAlidar sesion con MacAddress 
            _t = new System.Timers.Timer();
            _t.AutoReset = false;
            _t.Elapsed += new System.Timers.ElapsedEventHandler(ValidarMacAddress);
            //_t.Interval = 60000; // Verificar si la sesion esta activa cada minuto
            _t.Interval = 10000; // Verificar si la sesion esta activa cada Segundo
            _t.Start();
            LabelHola.Content += " " + sesion.UserName + "!";
        

          //  dbo_Sec_MenuUser MenuUser = new dbo_Sec_MenuUser();
           // DataTable RFCs = MenuUser.Get_RFCs_Menu_By_Id(sesion.IdUsuario);
          DataTable RFCs=  ValidacionCodigo.ValidacionRFCLicencia(sesion.IdUsuario,sesion.UserName);
         
            int MiIndex = 0;

            for (int i = 0; i < RFCs.Rows.Count; i++)
            {
                if (RFCs.Rows[i][0].ToString().Equals(sesion.RFC))
                {
                    MiIndex = i;
                }
            }

                RFCs_ComboBox.DataContext = RFCs;
                RFCs_ComboBox.SelectedIndex = MiIndex;

        

            Grid_Elements.Child = null;
            Grid_Elements.Child = new MainWindowImagen(ref _sesion);
        }

   
        
        public UsuarioActivo Sesion { 
            get {
                _sesion.ActualizaFecha(); // Actualizamos la fecha de expiracion de la sesion
                return this._sesion; 
            }
        }

        private void ValidarSesion(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!_sesion.ChecarFecha())
            {
                // Ocultamos primero la ventana para que ya no pueda seguir haciendo cosas
                this.Dispatcher.Invoke(new System.Action(() =>
                {
                    this.Hide();
                }), null);      
          
                MessageBox.Show("La sesión expiró");
                
                // Cerramos la ventana
                this.Dispatcher.Invoke(new System.Action(() =>
                {
                    this.Close();
                }), null);                
            }
            _t.Start();
        }
        private void ValidarMacAddress(object sender, System.Timers.ElapsedEventArgs e)
        {
            //Obetenemos el MacAddres de la ultima sesion guardada y en caso contrario de que no sea la misma las cerrara la seion 
            var mAddress = dbo_Sec_Usuario.Get_Usuario_Por_UserName(_sesion.UserName).Rows[0];
            if (!_sesion.MacAddres.Equals(mAddress["Mac_Address"].ToString()))
            {
                // Ocultamos primero la ventana para que ya no pueda seguir haciendo cosas
                this.Dispatcher.Invoke(new System.Action(() =>
                {
                    this.Hide();
                }), null);

                MessageBox.Show("La sesión ah sido iniciada en otro equipo.");

                // Cerramos la ventana
                this.Dispatcher.Invoke(new System.Action(() =>
                {
                    this.Close();
                }), null);
            }
            _t.Start();
        }


        private void ButtonVentas_Click_1(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_Ventas(ref _sesion);
        }

        private void ButtonCompras_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_Compras(ref _sesion);
        }

        private void ButtonInventarios_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_Inventarios(ref _sesion);
        }

        private void ButtonBancos_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_Bancos(ref _sesion);
        }

        private void ButtonCapitalHumano_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_CapitalHumano(ref _sesion);
        }

        private void Window_SizeChanged_1(object sender, SizeChangedEventArgs e)
        {

        }

        private void Window_LayoutUpdated_1(object sender, EventArgs e)
        {

        }

        private void ButtonConfiguracion_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_Configuracion(ref _sesion);
        }

        private void ButtonMiPerfil_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_MiPerfil(ref _sesion);
        }

        private void ButtonCRM_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_CRM(ref _sesion);
        }

        private void ButtonInformes_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_Informes(ref _sesion);
        }

        private void ButtonPuntoVenta_Click(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new Menu_PuntoVenta(ref _sesion);

        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown(0); // Cerrar definitivamente la aplicacion
        }

        private void RFCs_ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView currentItem = (DataRowView)RFCs_ComboBox.SelectedItem;
            _sesion.RFC = (string)currentItem.Row[0];
            Grid_Elements.Child = null;

            SIIE_ERP.BaseDatos.Configuracion.Empresa.dbo_Cat_Empresa Cat_Empresa = new SIIE_ERP.BaseDatos.Configuracion.Empresa.dbo_Cat_Empresa(_sesion.RFC, _sesion.UserName);
            //Label_RazonSocial.Content = Cat_Empresa.Get_Empresas().Rows[0]["Nombre_Comercial"].ToString();

            dbo_Sec_MenuUser MenuU = new dbo_Sec_MenuUser();
            DataTable ds_Menu = MenuU.Get_Menus_by_RFC(_sesion.IdUsuario, _sesion.RFC);


            ButtonVentas.Visibility = System.Windows.Visibility.Hidden;
            ButtonInventarios.Visibility = System.Windows.Visibility.Hidden;
            ButtonCapitalHumano.Visibility = System.Windows.Visibility.Hidden;
            ButtonConfiguracion.Visibility = System.Windows.Visibility.Hidden;
            ButtonMiPerfil.Visibility = System.Windows.Visibility.Hidden;
            ButtonCompras.Visibility = System.Windows.Visibility.Hidden;
            ButtonBancos.Visibility = System.Windows.Visibility.Hidden;
            ButtonCRM.Visibility = System.Windows.Visibility.Hidden;
            ButtonInformes.Visibility = System.Windows.Visibility.Hidden;
            ButtonPuntoVenta.Visibility = System.Windows.Visibility.Hidden;

            int MyPlace = 1;

            for (int i = 0; i < ds_Menu.Rows.Count; i++) { 
            
                if(Int32.Parse( ds_Menu.Rows[i]["IdMenu"].ToString()) == 10 && Boolean.Parse( ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonVentas.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonVentas, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 20 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonInventarios.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonInventarios, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 30 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonCapitalHumano.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonCapitalHumano, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 60 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonCompras.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonCompras, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 70 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonBancos.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonBancos, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 80 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonCRM.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonCRM, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 90 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonInformes.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonInformes, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 100 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonPuntoVenta.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonPuntoVenta, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 40 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonConfiguracion.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonConfiguracion, MyPlace);
                    MyPlace++;
                }
                else if (Int32.Parse(ds_Menu.Rows[i]["IdMenu"].ToString()) == 50 && Boolean.Parse(ds_Menu.Rows[i]["IsActive"].ToString()) == true)
                {
                    ButtonMiPerfil.Visibility = System.Windows.Visibility.Visible;
                    Grid.SetColumn(ButtonMiPerfil, MyPlace);
                    MyPlace++;
                }
            }

            // Cargamos la informacion relacionada con el PV del usuario activo

            var db = new SIIE_ERP.BaseDatos.PuntoVenta.Catalogos.dbo_Cat_Terminal(_sesion.RFC, _sesion.UserName);
            var t = db.Get_Terminal_Abierta() as DataRow;

            if (t != null)
            {
                _sesion.PV_CajaIsOpen = true;
                _sesion.PV_Id_Terminal = Int32.Parse(t["Id_Terminal"].ToString());
            }
        }

        private void ButtonCerrarSesion_Click(object sender, RoutedEventArgs e)
        {
            Login.Login Login = new Login.Login();
            Login.Show();
            this.Hide();  
        }

        private void Window_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void ButtonHome_Click_1(object sender, RoutedEventArgs e)
        {
            Grid_Elements.Child = null;
            Grid_Elements.Child = new MainWindowImagen(ref _sesion);
        }
    }
}
